
package org.sopt.dev.ImgKnight.frontier.Filter;

import java.net.URL;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

import org.sopt.dev.ImgKnight.frontier.Frontier;

public class ExternalUrlFilter {

	private Frontier frontier = null;
	
	private Logger serviceLogger = null;
	
	public ExternalUrlFilter() {
		frontier = Frontier.getInstance();
		serviceLogger = Logger.getLogger("frontier.service");
	}
	
	public boolean validate(URL url) {
		if( !frontier.getFrontierConfig().FetchExternalUrl ) {
			String hostUrl = url.getHost();
			if( frontier.getFrontierConfig().containsSeedUrl(hostUrl) ) {
				serviceLogger.debug("Allow: " + url);
				return true;
			}
			StringTokenizer tokenizer = new StringTokenizer(hostUrl, ".");
			while( tokenizer.hasMoreTokens() ) {
				String token = tokenizer.nextToken();
				if( token.length() > 2 && 
					!token.equals("com") && !token.equals("net") && !token.equals("www") ) {
					if( frontier.getFrontierConfig().equalsSeedUrl(token) ) {
						serviceLogger.debug("Allow: " + url);
						return true;
					}
				}
			}
			return false;
		}
		return true;
	}
	
}
